#include "alertmanager.h"
#include "ui_alertmanager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QInputDialog>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QLabel>
#include <QComboBox>
#include "alibabasendphoneclient.h"


AlertManager::AlertManager(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::AlertManager)
    ,common(this)
{
    ui->setupUi(this);
    setupModel();
    setupConnections();
    common.loadQssfromfile(":/qss/AlertManager.qss");
    ui->showRuleTableView->setSelectionMode(QAbstractItemView::MultiSelection);
    // 设置定时任务每隔 30 秒执行一次 checkAlerts
    alertTimer = new QTimer(this);
    connect(alertTimer, &QTimer::timeout, this, &AlertManager::checkAlerts);
    alertTimer->start(30000); // 30 秒
    qDebug() << "定时器已启动，每隔 30 秒执行一次 checkAlerts";
}

AlertManager::~AlertManager()
{
    delete ui;
}

void AlertManager::setupModel()
{
    db = SQLiteDatabase::getInstance();
    model = new QStandardItemModel(this);
    model->setColumnCount(6);
    model->setHeaderData(0, Qt::Horizontal, tr("选择"));
    model->setHeaderData(1, Qt::Horizontal, tr("规则ID"));
    model->setHeaderData(2, Qt::Horizontal, tr("设备ID"));
    model->setHeaderData(3, Qt::Horizontal, tr("规则描述"));
    model->setHeaderData(4, Qt::Horizontal, tr("告警条件"));
    model->setHeaderData(5, Qt::Horizontal, tr("告警动作"));

    QSqlQuery query(db->getConnection());
    query.prepare("SELECT * FROM alarm_rules");
    if (!query.exec()) {
        qCritical() << "Failed to load alarm rules:" << query.lastError().text();
        return;
    }

    while (query.next()) {
        QList<QStandardItem *> rowItems;
        QStandardItem *checkItem = new QStandardItem();
        checkItem->setCheckable(true);
        rowItems.append(checkItem);
        rowItems.append(new QStandardItem(query.value("rule_id").toString()));
        rowItems.append(new QStandardItem(query.value("device_id").toString()));
        rowItems.append(new QStandardItem(query.value("description").toString()));
        rowItems.append(new QStandardItem(query.value("condition").toString()));
        rowItems.append(new QStandardItem(query.value("action").toString()));
        model->appendRow(rowItems);
    }

    ui->showRuleTableView->setModel(model);
    ui->showRuleTableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); //自适应
}

void AlertManager::setupConnections()
{
    connect(ui->addRuleBtn, &QAbstractButton::clicked, this, &AlertManager::onAddAlertRule);
    connect(ui->editeRuleBtn, &QAbstractButton::clicked, this, &AlertManager::onEditAlertRule);
    connect(ui->deleteRuleBtn, &QAbstractButton::clicked, this, &AlertManager::onDeleteAlertRule);
    connect(ui->deleteBatchRuleBtn,&QAbstractButton::clicked, this, &AlertManager::onBatchDeleteAlertRules);
}

void AlertManager::onAddAlertRule()
{
    Logger().logInfo("添加规则");
    QDialog dialog(this);
    dialog.setWindowTitle("添加告警规则");

    QVBoxLayout layout(&dialog);

    QLineEdit descriptionEdit;
    QComboBox fieldComboBox;
    QComboBox operatorComboBox;
    QLineEdit valueEdit;
    QComboBox actionComboBox;
    QComboBox deviceComboBox;

    layout.addWidget(new QLabel("告警描述:"));
    layout.addWidget(&descriptionEdit);
    layout.addWidget(new QLabel("告警字段:"));
    layout.addWidget(&fieldComboBox);
    layout.addWidget(new QLabel("操作符:"));
    layout.addWidget(&operatorComboBox);
    layout.addWidget(new QLabel("告警值:"));
    layout.addWidget(&valueEdit);
    layout.addWidget(new QLabel("告警动作:"));
    layout.addWidget(&actionComboBox);
    layout.addWidget(new QLabel("设备名称:"));
    layout.addWidget(&deviceComboBox);

    // 填充告警字段下拉框
    fieldComboBox.addItem("temperature");
    fieldComboBox.addItem("humidity");
    fieldComboBox.addItem("light");
    fieldComboBox.addItem("co2");
    fieldComboBox.addItem("pressure");

    // 填充操作符下拉框
    operatorComboBox.addItem(">");
    operatorComboBox.addItem("<");
    operatorComboBox.addItem(">=");
    operatorComboBox.addItem("<=");
    operatorComboBox.addItem("==");

    // 填充告警动作下拉框
    actionComboBox.addItem("打电话");
    actionComboBox.addItem("发邮件");

    // 填充设备名称
    db = SQLiteDatabase::getInstance();
    QSqlQuery query(db->getConnection());
    query.prepare("SELECT name FROM devices");
    if (!query.exec()) {
        common.createMessageBox("错误", "找不到该设备名称");
        //QMessageBox::critical(this, "Database Error", "找不到该设备名称");
        qDebug() << "Failed to load device names:" << query.lastError().text();
        return;
    }
    while (query.next()) {
        deviceComboBox.addItem(query.value(0).toString());
    }

    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    layout.addWidget(&buttonBox);

    connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        QString description = descriptionEdit.text();
        QString field = fieldComboBox.currentText();
        QString op = operatorComboBox.currentText();
        QString value = valueEdit.text();
        QString action = actionComboBox.currentText();
        QString deviceName = deviceComboBox.currentText();

        if (description.isEmpty() || field.isEmpty() || op.isEmpty() || value.isEmpty() || action.isEmpty() || deviceName.isEmpty()) {
            //QMessageBox::warning(this, "输入错误", "所有字段都是必填的！");
            common.createMessageBox("提示", "所有字段都是必填的！");
            return;
        }

        // 生成告警条件
        QString condition = QString("%1 %2 %3").arg(field).arg(op).arg(value);

        // 获取设备 ID
        query.prepare("SELECT device_id FROM devices WHERE name = ?");
        query.addBindValue(deviceName);
        if (!query.exec() || !query.next()) {
            //QMessageBox::critical(this, "Database Error", "Device not found");
            common.createMessageBox("错误", "未找到设备");
            return;
        }
        int deviceId = query.value(0).toInt();

        QSqlQuery insertQuery(db->getConnection());
        insertQuery.prepare("INSERT INTO alarm_rules (device_id, description, condition, action) VALUES (?, ?, ?, ?)");
        insertQuery.addBindValue(deviceId);
        insertQuery.addBindValue(description);
        insertQuery.addBindValue(condition);
        insertQuery.addBindValue(action);

        if (!insertQuery.exec()) {
            //QMessageBox::critical(this, "Database Error", "Failed to insert alarm rule");
            common.createMessageBox("错误", "新增告警规则失败");
            qDebug() << "Failed to insert alarm rule:" << insertQuery.lastError().text();
            return;
        }

        // 获取新插入记录的ID
        int ruleId = insertQuery.lastInsertId().toInt();

        // 添加新行到模型中
        QList<QStandardItem *> rowItems;
        QStandardItem *checkItem = new QStandardItem();
        checkItem->setCheckable(true);
        rowItems.append(checkItem);
        rowItems.append(new QStandardItem(QString::number(ruleId)));
        rowItems.append(new QStandardItem(QString::number(deviceId)));
        rowItems.append(new QStandardItem(description));
        rowItems.append(new QStandardItem(condition));
        rowItems.append(new QStandardItem(action));
        model->appendRow(rowItems);
    }
}

void AlertManager::onEditAlertRule()
{
    Logger().logInfo("编辑规则");
    QModelIndex index = ui->showRuleTableView->currentIndex();
    if (!index.isValid()) {
        //QMessageBox::warning(this, "选择错误", "请选择要编辑的规则！");
        common.createMessageBox("提示", "请选择要编辑的规则！");
        return;
    }

    int ruleId = model->data(model->index(index.row(), 1)).toInt();
    QString description = model->data(model->index(index.row(), 3)).toString();
    QString condition = model->data(model->index(index.row(), 4)).toString();
    QString action = model->data(model->index(index.row(), 5)).toString();

    QDialog dialog(this);
    dialog.setWindowTitle("修改告警规则");

    QVBoxLayout layout(&dialog);

    QLineEdit descriptionEdit;
    QComboBox fieldComboBox;
    QComboBox operatorComboBox;
    QLineEdit valueEdit;
    QComboBox actionComboBox;

    // 解析现有的告警条件
    QStringList conditionParts = condition.split(" ");
    if (conditionParts.size() == 3) {
        fieldComboBox.addItem(conditionParts[0]);
        operatorComboBox.addItem(conditionParts[1]);
        valueEdit.setText(conditionParts[2]);
    } else {
        // 填充告警字段下拉框
        fieldComboBox.addItem("temperature");
        fieldComboBox.addItem("humidity");
        fieldComboBox.addItem("light");
        fieldComboBox.addItem("co2");
        fieldComboBox.addItem("pressure");

        // 填充操作符下拉框
        operatorComboBox.addItem(">");
        operatorComboBox.addItem("<");
        operatorComboBox.addItem(">=");
        operatorComboBox.addItem("<=");
        operatorComboBox.addItem("==");
    }

    // 填充告警动作下拉框
    actionComboBox.addItem("打电话");
    actionComboBox.addItem("发邮件");
    actionComboBox.setCurrentText(action);

    descriptionEdit.setText(description);

    layout.addWidget(new QLabel("告警描述:"));
    layout.addWidget(&descriptionEdit);
    layout.addWidget(new QLabel("告警字段:"));
    layout.addWidget(&fieldComboBox);
    layout.addWidget(new QLabel("操作符:"));
    layout.addWidget(&operatorComboBox);
    layout.addWidget(new QLabel("告警值:"));
    layout.addWidget(&valueEdit);
    layout.addWidget(new QLabel("告警动作:"));
    layout.addWidget(&actionComboBox);

    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    layout.addWidget(&buttonBox);

    connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        description = descriptionEdit.text();
        QString field = fieldComboBox.currentText();
        QString op = operatorComboBox.currentText();
        QString value = valueEdit.text();
        action = actionComboBox.currentText();

        if (description.isEmpty() || field.isEmpty() || op.isEmpty() || value.isEmpty() || action.isEmpty()) {
            //QMessageBox::warning(this, "输入错误", "所有字段都是必填的！");
            common.createMessageBox("警告", "所有字段都是必填的！");
            return;
        }

        // 生成新的告警条件
        QString newCondition = QString("%1 %2 %3").arg(field).arg(op).arg(value);

        QSqlQuery updateQuery(db->getConnection());
        updateQuery.prepare("UPDATE alarm_rules SET description = ?, condition = ?, action = ? WHERE rule_id = ?");
        updateQuery.addBindValue(description);
        updateQuery.addBindValue(newCondition);
        updateQuery.addBindValue(action);
        updateQuery.addBindValue(ruleId);

        if (!updateQuery.exec()) {
            //QMessageBox::critical(this, "Database Error", "Failed to update alarm rule");
            common.createMessageBox("错误", "更新告警规则失败");
            qDebug() << "Failed to update alarm rule:" << updateQuery.lastError().text();
            return;
        }

        // 更新模型中的数据
        model->setData(model->index(index.row(), 3), description);
        model->setData(model->index(index.row(), 4), newCondition);
        model->setData(model->index(index.row(), 5), action);
    }
}

void AlertManager::onDeleteAlertRule()
{
    Logger().logInfo("删除规则");
    QModelIndex index = ui->showRuleTableView->currentIndex();
    if (!index.isValid()) {
        //QMessageBox::warning(this, "删除错误", "请选择要删除的规则！");
        common.createMessageBox("警告", "请选择要删除的规则！");
        return;
    }

    int ruleId = model->data(model->index(index.row(), 1)).toInt();

    // 弹出确认删除的警告框
    // QMessageBox::StandardButton reply;
    // reply = QMessageBox::question(this, "确认删除", "你确定要删除这个规则吗？",
    //                               QMessageBox::Yes | QMessageBox::No);
    // if (reply == QMessageBox::Yes) {
    //     SQLiteDatabase* db = SQLiteDatabase::getInstance();
    //     db->deleteRecord("alarm_rules", QString("rule_id = %1").arg(ruleId));
    //     model->removeRow(index.row());
    //     Logger().logInfo("规则已删除");
    // } else {
    //     Logger().logInfo("取消删除规则");
    // }
    bool res=common.createMessageBox("选择", "你确定要删除这个规则吗？");
    if(res){
        SQLiteDatabase* db = SQLiteDatabase::getInstance();
        db->deleteRecord("alarm_rules", QString("rule_id = %1").arg(ruleId));
        model->removeRow(index.row());
        Logger().logInfo("规则已删除");
    }else{
        Logger().logInfo("取消删除规则");
    }
}

void AlertManager::onBatchDeleteAlertRules()
{
    Logger().logInfo("批量删除规则");

    // 获取模型中的行数
    int rowCount = model->rowCount();

    // 用于存储选中的行的索引
    QList<int> selectedRows;

    // 遍历所有行，检查复选框是否勾选
    for (int row = 0; row < rowCount; ++row) {
        QStandardItem *item = model->item(row, 0); // 假设复选框在第0列
        if (item && item->checkState() == Qt::Checked) {
            selectedRows.append(row);
        }
    }

    if (selectedRows.isEmpty()) {
        //QMessageBox::warning(this, "批量删除", "请选择要删除的规则！");
        common.createMessageBox("警告", "请选择要删除的规则！");
        return;
    }

    // 弹出确认删除的警告框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认批量删除", "你确定要删除选中的规则吗？",
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes) {
        SQLiteDatabase* db = SQLiteDatabase::getInstance();

        bool success = true;
        for (int row : selectedRows) {
            int ruleId = model->data(model->index(row, 1)).toInt();
            QString condition = QString("rule_id = %1").arg(ruleId);
            if (!db->deleteRecords("alarm_rules", condition)) {
                success = false;
                qCritical() << "Failed to delete rule with ID:" << ruleId;
                break;
            }
        }

        if (success) {
            Logger().logInfo("选中的规则已删除");

            // 从模型中移除选中的行
            std::sort(selectedRows.begin(), selectedRows.end(), std::greater<int>());
            for (int row : selectedRows) {
                model->removeRow(row);
            }
        } else {
            //QMessageBox::critical(this, "批量删除", "批量删除失败，请重试！");
            common.createMessageBox("错误", "批量删除失败，请重试！");
        }
    } else {
        Logger().logInfo("取消批量删除规则");
    }
}

void AlertManager::ReceiveLogininformation(QString &userName, QString &role)
{
    qDebug()<<userName<<role;
    if(role=="user"){
        ui->addRuleBtn->setEnabled(false);
        ui->editeRuleBtn->setEnabled(false);
        ui->deleteRuleBtn->setEnabled(false);
        ui->deleteBatchRuleBtn->setEnabled(false);
        ui->addRuleBtn->setVisible(false);
        ui->editeRuleBtn->setVisible(false);
        ui->deleteRuleBtn->setVisible(false);
        ui->deleteBatchRuleBtn->setVisible(false);
    }
}
void AlertManager::checkAlerts()
{
    Logger().logInfo("定时检测功能开启");
    // qDebug()<<"chekAlert已经启动";
    db = SQLiteDatabase::getInstance();
    QSqlQuery ruleQuery(db->getConnection());
    ruleQuery.prepare("SELECT rule_id, device_id, condition FROM alarm_rules");

    if (!ruleQuery.exec()) {
        qCritical() << "无法获取报警规则:" << ruleQuery.lastError().text();
        return;
    }

    while (ruleQuery.next()) {
        int ruleId = ruleQuery.value("rule_id").toInt();
        int  deviceId = ruleQuery.value("device_id").toInt();
        qDebug()<<deviceId;
        QString condition = ruleQuery.value("condition").toString();
        qDebug()<<condition;
        QSqlQuery dataQuery(db->getConnection());
        QString queryString = QString("SELECT * FROM data WHERE device_id = %1 AND %2").arg(deviceId).arg(condition);
        dataQuery.prepare(queryString);

        if (!dataQuery.exec()) {
            qCritical() << "无法获取到规则的数据:" << ruleQuery.lastError().text();
            continue;
        }

        while (dataQuery.next()) {
            QString content = QString("Device ID: %1, Condition: %2, DataID: %3")
                                  .arg(deviceId)
                                  .arg(condition)
                                  .arg(dataQuery.value("data_id").toString());
            triggerAlert(deviceId, content);
            qDebug()<<content;
        }
    }
}

void AlertManager::triggerAlert(int deviceId, const QString &content)
{
    qDebug()<<"触发告警记录";
    Logger().logInfo("触发告警记录");
    // 获取设备名称
    db = SQLiteDatabase::getInstance();
    QSqlQuery query(db->getConnection());
    query.prepare("SELECT name FROM devices WHERE device_id = ?");
    query.addBindValue(deviceId);
    if (!query.exec() || !query.next()) {
        qCritical() << "获取设备名称失败:" << query.lastError().text();
        return;
    }
    QString deviceName = query.value(0).toString();

    // 获取当前时间
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

    // 检查是否已经存在相同的告警记录
    QSqlQuery checkQuery(db->getConnection());
    checkQuery.prepare("SELECT COUNT(*) FROM alarm_records WHERE device_id = ? AND content = ? AND status = '未'");
    checkQuery.addBindValue(deviceId);
    checkQuery.addBindValue(content);
    if (!checkQuery.exec() || !checkQuery.next()) {
        qCritical() << "检查告警记录失败:" << checkQuery.lastError().text();
        return;
    }
    int count = checkQuery.value(0).toInt();
    if (count > 0) {
        qDebug() << "相同的告警记录已经存在，不插入新的记录";
        return;
    }

    // 记录告警到数据库
    query.prepare("INSERT INTO alarm_records (device_id, timestamp, content, status, note) VALUES (?, ?, ?, ?, ?)");
    query.addBindValue(deviceId);
    query.addBindValue(timestamp);
    query.addBindValue(content);
    query.addBindValue("未");
    query.addBindValue("");
    if (!query.exec()) {
        qCritical() << "插入告警记录失败:" << query.lastError().text();
        return;
    }

    // // 打印调试信息
    // qDebug() << "设备ID:" << deviceId;
    // qDebug() << "设备名称:" << deviceName;
    // qDebug() << "告警内容:" << content;
    // qDebug() << "Timestamp:" << timestamp;

    // 发送通知
    sendNotification(deviceId, deviceName, content, timestamp);
}

void AlertManager::sendNotification(int deviceId, const QString &deviceName, const QString &content, const QString &timestamp)
{
    SQLiteDatabase* db = SQLiteDatabase::getInstance();

    // 获取通知设置
    QJsonArray settings = db->read("notice_settings", "");
    if (settings.isEmpty()) {
        qCritical() << "Failed to retrieve notice settings.";
        return;
    }

    // 构建通知内容
    QString notificationContent = QString("设备名称: %1\n告警时间: %2\n告警内容: %3")
                                      .arg(deviceName)
                                      .arg(timestamp)
                                      .arg(content);

    // 打印调试信息
    qDebug() << "设备ID:" << deviceId;
    qDebug() << "设备名称:" << deviceName;
    qDebug() << "告警内容:" << content;
    qDebug() << "Timestamp:" << timestamp;
    qDebug() << "notificationContent" << notificationContent;

    for (const QJsonValue& setting : settings) {
        QJsonObject obj = setting.toObject();
        QString email = obj["email"].toString();
        QString phone = obj["phone"].toString();

        // 打印邮件和短信信息
        if (!email.isEmpty()) {
            qDebug() << "Sending email to:" << email;
        }

        if (!phone.isEmpty()) {
            qDebug() << "Sending phone to:" << phone;
        }

        // 记录通知历史
        QJsonObject history;
        if (!email.isEmpty()) {
            history["method"] = "Email";
            history["timestamp"] = timestamp;
            history["content"] = notificationContent;
            db->create("notice_history", history);
        }

        if (!phone.isEmpty()) {
            history["method"] = "Phone";
            history["timestamp"] = timestamp;
            history["content"] = notificationContent;
            db->create("notice_history", history);
        }
    }
}
